﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Model;
using BusinessLogic.Command;
using System.Globalization;
using System.Configuration;
using System.IO;

namespace CO9APPFORM
{
    public partial class Application : System.Web.UI.Page
    {
        public int TabActive
        {
            get
            {
                return mtvTab.ActiveViewIndex;
            }
            set
            {
                LinkButton[] lbt = new LinkButton[4];

                mtvTab.ActiveViewIndex = value;
                int i;

                for (i = 0; i < 4; i++)
                {
                    lbt[i] = (LinkButton)pnlTabHead.FindControl("lnkTab" + i.ToString());
                    if(Convert.ToInt16(DSPersonal.TX_STATUS) > i )
                        lbt[i].CssClass = "done";
                    else
                        lbt[i].CssClass = "";
                }

                if (value < 4)
                {
                    lbt[value].CssClass = "active";
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                try
                {
                    LoadPersonalInfo();

                    TabActive = DSPersonal.TX_STATUS != null && DSPersonal.TX_STATUS != "" ? Convert.ToInt16(DSPersonal.TX_STATUS) : 0;

                    BindControl(TabActive);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

        protected void TabHead_Click(object sender, EventArgs e)
        {
            LinkButton lb = (LinkButton)sender;
            lb.CssClass = "active";
            TabActive = Int16.Parse(lb.CommandArgument);

            LoadPersonalInfo();

            BindControl(TabActive);
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            TabActive--;
        }

        protected void LoadPersonalInfo()
        {
            string hash = Request.QueryString["hash"];
            var P = new GetPersonalInfoCommand(hash);
            P.Execute();
            DSPersonal = P.Result;

        }

        protected void BindControl(int tabId)
        {
            switch (tabId)
            {
                case 0: 
                    BindTab1(); 
                    break;
                
                case 1:
                    LoadFamilyEducationInfo();
                    break;
                case 2:
                    LoadEmployer();
                    BindTab3(); 
                    break;
                case 3:
                    LoadSkillAndLang();
                    BindTab4(); 
                    break;
                case 4:
                    LoadSalary();
                    break;                
            }
        }

        protected void RefreshAllDataSource()
        {
            GetPersonalInfoCommand pcmd = new GetPersonalInfoCommand(DSPersonal.ID);
            pcmd.Execute();
            DSPersonal = pcmd.Result;

            ViewState["EmployerList"] = null;
            ViewState["LanguageDataSource"] = null;
            ViewState["FamilyList"] = null;
            ViewState["EducationList"] = null;
        }

        #region Tab1

        private APP_PERSONAL DSPersonal
        {
            get
            {
                APP_PERSONAL result = new APP_PERSONAL();

                if (ViewState["Personal"] != null)
                {
                    result = (APP_PERSONAL)ViewState["Personal"];
                }

                return result;
            }
            set
            {
                ViewState["Personal"] = value;
            }
        }
       
        protected void BindTab1()
        {
            CubeOfDB2Entities db = new CubeOfDB2Entities();
            ddlPositionApplyFor.DataSource = db.APP_POSITION.ToList();
            ddlPositionApplyFor.DataTextField = "NAME_EN";
            ddlPositionApplyFor.DataValueField = "NAME_EN";
            ddlPositionApplyFor.DataBind();
            ddlPositionApplyFor.Items.Insert(0, new ListItem("Please Select", ""));

            txtHeight.Text = DSPersonal.HEIGHT;
            ddlBloodGroup.SelectedValue = DSPersonal.BLOOD_GROUP;
            ddlMilitaryService.SelectedValue = DSPersonal.MILITARY;

            if (DSPersonal.BIRTH_DATE != null)
            {
                DateTime dt = Convert.ToDateTime(DSPersonal.BIRTH_DATE);
                String strDate = "";
                strDate = dt.ToString("dd MMMM yyyy");
                txtDateOfBirth.Text = strDate;
            }
            else
                txtDateOfBirth.Text = "";

            txtAge.Text = Convert.ToString(DSPersonal.AGE);
            ddlGender.SelectedValue = DSPersonal.GENDER;
            ddlNationality.SelectedValue = DSPersonal.NATIONALITY;
            ddlReligion.SelectedValue = DSPersonal.RELIGION;
            txtWeight.Text = DSPersonal.WEIGHT;
            txtPlaceOfBirth.Text = DSPersonal.BIRTH_PLACE;
            ddlMaritalStatus.SelectedValue = DSPersonal.MARITAL;

            if (DSPersonal.APP_DATE != null)
            {
                DateTime dt = Convert.ToDateTime(DSPersonal.APP_DATE);
                String strDate = "";
                strDate = dt.ToString("dd MMMM yyyy");
                txtApplyDate.Text = strDate;
            }
            else
                txtApplyDate.Text = "";

            ddlPositionApplyFor.SelectedValue = DSPersonal.POSITION;

            if (DSPersonal.SRT_DATE != null)
            {
                DateTime dt = Convert.ToDateTime(DSPersonal.SRT_DATE);
                String strDate = "";
                strDate = dt.ToString("dd MMMM yyyy");
                txtAvailableStartDate.Text = strDate;
            }
            else
                txtAvailableStartDate.Text = "";

            txtHowTo_Note.Text = DSPersonal.HOWTO_NOTE;
            txtNameTH.Text = DSPersonal.FNAME_TH;
            txtNameEN.Text = DSPersonal.FNAME_EN;
            txtSurnameTH.Text = DSPersonal.LNAME_TH;
            txtSurnameEN.Text = DSPersonal.LNAME_EN;
            txtNicknameTH.Text = DSPersonal.NNAME_TH;
            txtNicknameEN.Text = DSPersonal.NNAME_EN;
            txtPresentAddress.Text = DSPersonal.ADDRESS;
            txtProvince.Text = DSPersonal.PROVINCE;
            txtPostcode.Text = DSPersonal.POSTCODE;
            txtEmailAddress.Text = DSPersonal.EMAIL;
            txtTelephone.Text = DSPersonal.TEL;
            txtMobile.Text = DSPersonal.MOBILE;
            if (DSPersonal.IMG != null && DSPersonal.IMG != "")
            {
                txtFileName.Text = DSPersonal.IMG;
                Image1.ImageUrl = ConfigurationManager.AppSettings["UploadPath"].ToString() + txtFileName.Text;
            }
            else
                txtFileName.Text = "";

            /* Family and Education */
            if (DSPersonal.IS_STUDYING == "Y")
            {
                chkIsStudying.Checked = true;
                dvStudying.Visible = true;
            }
            else
            {
                chkIsStudying.Checked = false;
                dvStudying.Visible = false;
            }
            txtAtInstitute.Text = DSPersonal.STUDYING_INSTITUTE;
            txtMajor2.Text = DSPersonal.STUDYING_MAJOR;
            txtClassScheduleDate.Text = DSPersonal.STUDYING_CLASS;
            txtFinishOn.Text = DSPersonal.STUDYING_FINISHON;
        }

        protected void btnTab1SaveDraft_Click(object sender, EventArgs e)
        {
            SavePersonalInfo();
        }
        
        protected void btnTab1Next_Click(object sender, EventArgs e)
        {
            SavePersonalInfo();
            TabActive++;
        }

        protected void SavePersonalInfo()
        {
            var P = DSPersonal;

            if (FileUpload1.HasFile)
            {
                if (FileUpload1.PostedFile.FileName.Length > Convert.ToInt16(ConfigurationManager.AppSettings["UploadFileNameCharactorLength"].ToString()))
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "ErrorUploadMsg2", "alert('File name are not allow over than '" + ConfigurationManager.AppSettings["UploadFileNameCharactorLength"].ToString() + "' Charactors');", true);
                    return;
                }
                if (FileUpload1.PostedFile.ContentLength > Convert.ToInt32(ConfigurationManager.AppSettings["UploadFilesSize"].ToString()))
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "ErrorUploadMsg2", "alert('File size are not allow over than '" + ConfigurationManager.AppSettings["UploadFilesSize"].Substring(0, 1).ToString() + "' KB');", true);
                    return;
                }
                if ((Path.GetExtension(FileUpload1.FileName).ToLower() == ".gif") ||
                (Path.GetExtension(FileUpload1.FileName).ToLower() == ".png") ||
                (Path.GetExtension(FileUpload1.FileName).ToLower() == ".jpeg") ||
                (Path.GetExtension(FileUpload1.FileName).ToLower() == ".jpg"))
                {
                    string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
                    FileUpload1.PostedFile.SaveAs(Server.MapPath(ConfigurationManager.AppSettings["UploadPath"].ToString()) + txtNameEN.Text + "_" + txtSurnameEN.Text + "_" + fileName);
                    P.IMG = txtNameEN.Text + "_" + txtSurnameEN.Text + "_" + fileName;
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "ErrorUploadMsg3", "alert('File uploading must has an extension name as .gif, .png, .jpeg, .jpg');", true);
                    return;
                }
            }
            else
                P.IMG = txtFileName.Text;

            P.HEIGHT = txtHeight.Text;
            P.BLOOD_GROUP = ddlBloodGroup.SelectedValue;
            P.MILITARY = ddlMilitaryService.SelectedValue;
            P.BIRTH_DATE = Convert.ToDateTime(txtDateOfBirth.Text);
            P.AGE = Convert.ToInt32(txtAge.Text);
            P.GENDER = ddlGender.SelectedValue;
            P.NATIONALITY = ddlNationality.SelectedValue;
            P.RELIGION = ddlReligion.SelectedValue;
            P.WEIGHT = txtWeight.Text;
            P.BIRTH_PLACE = txtPlaceOfBirth.Text;
            P.MARITAL = ddlMaritalStatus.SelectedValue;
            P.APP_DATE = Convert.ToDateTime(txtApplyDate.Text);
            P.POSITION = ddlPositionApplyFor.SelectedValue;
            P.SRT_DATE = Convert.ToDateTime(txtAvailableStartDate.Text);
            P.HOWTO_NOTE = txtHowTo_Note.Text;
            P.FNAME_TH = txtNameTH.Text;
            P.FNAME_EN = txtNameEN.Text;
            P.LNAME_TH = txtSurnameTH.Text;
            P.LNAME_EN = txtSurnameEN.Text;
            P.NNAME_TH = txtNicknameTH.Text;
            P.NNAME_EN = txtNicknameEN.Text;
            P.ADDRESS = txtPresentAddress.Text;
            P.PROVINCE = txtProvince.Text;
            P.POSTCODE = txtPostcode.Text;
            P.EMAIL = txtEmailAddress.Text;
            P.TEL = txtTelephone.Text;
            P.MOBILE = txtMobile.Text;

            if(P.TX_STATUS == null || P.TX_STATUS == "")
                P.TX_STATUS = "1";

            var cmd = new MaintainPersonalInfo(P);
            cmd.Execute();

            if (P.IMG != null && P.IMG != string.Empty)
            {
                Image1.ImageUrl = ConfigurationManager.AppSettings["UploadPath"].ToString() + P.IMG;
            }
        }
        
        #endregion

        #region Tab2

        public List<APP_FAMILY> FamilyDataSource
        {
            get
            {
                if (ViewState["FamilyList"] == null)
                {
                    ViewState["FamilyList"] = DSPersonal.APP_FAMILY.ToList();
                }

                return (List<APP_FAMILY>)ViewState["FamilyList"];
            }
            set
            {
                ViewState["FamilyList"] = value;
            }
        }

        private void RunFamilyRowIndex(List<APP_FAMILY> list)
        {
            int i = 0;

            foreach (APP_FAMILY emp in list)
            {
                emp.GridIndex = ++i;
            }
        }

        public List<APP_EDUCATION> EducationDataSource
        {
            get
            {
                if (ViewState["EducationList"] == null)
                {
                    ViewState["EducationList"] = DSPersonal.APP_EDUCATION.ToList();
                }

                return (List<APP_EDUCATION>)ViewState["EducationList"];
            }
            set
            {
                ViewState["EducationList"] = value;
            }
        }

        private void RunEducationRowIndex(List<APP_EDUCATION> list)
        {
            int i = 0;

            foreach (APP_EDUCATION emp in list)
            {
                emp.GridIndex = ++i;
            }
        }

        protected void LoadFamilyEducationInfo()
        {
            LoadFamilyInfo();
            LoadEducationInfo();
        }

        /* Start Family Background Code */
        protected void LoadFamilyInfo()
        {
            if (DSPersonal.APP_FAMILY.Count == 0)
            {
                APP_FAMILY l = new APP_FAMILY
                {
                    act = ActionEnum.Dummy,
                    RELATION = "Father",
                    NAME = "** Example",
                    LOCATION = "Bangkok",
                    OCCUPATION = "Farmer"
                };

                FamilyDataSource.Add(l);
                hidFamily.Value = "";
            }
            else
            {
                hidFamily.Value = "1";
                FamilyDataSource = DSPersonal.APP_FAMILY.ToList();
            }

            BindTab2Family();
        }

        private void BindTab2Family()
        {
            RunFamilyRowIndex(FamilyDataSource);
            gvFamily.DataSource = FamilyDataSource.Where(o => o.act != ActionEnum.Delete).ToList();
            gvFamily.DataBind();

            if (FamilyDataSource.Where(o => o.act != ActionEnum.Delete && o.act != ActionEnum.Dummy).ToList().Count > 0)
                hidFamily.Value = "1";
            else
                hidFamily.Value = "";
        }

        protected void gvFamily_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "EditFamily")
            {
                hdFamilyID.Value = e.CommandArgument.ToString();
                EditFamily(Convert.ToInt16(e.CommandArgument));
            }
            else //Delete Family
            {
                DeleteFamily(Convert.ToInt16(e.CommandArgument));

                List<APP_FAMILY> lst = FamilyDataSource.Where(o => o.act != ActionEnum.Delete).ToList();
                if (lst.Count == 0)
                    hidFamily.Value = "";
                else
                    hidFamily.Value = "1";
            }
        }

        private void DeleteFamily(int id)
        {
            APP_FAMILY l = FamilyDataSource.Where(o => o.GridIndex == id).FirstOrDefault();
            if (l != null)
            {
                l.act = ActionEnum.Delete;
                BindTab2Family();
            }
        }

        private void EditFamily(int id)
        {
            APP_FAMILY l = FamilyDataSource.Where(o => o.GridIndex == id).FirstOrDefault();
            if (l != null)
            {
                l.act = ActionEnum.Edit;
                txtNameSurnanme.Text = l.NAME;
                ddlRelation.SelectedValue = l.RELATION;
                txtOccupation.Text = l.OCCUPATION;
                txtLocation.Text = l.LOCATION;

                dvEducation.Visible = false;
                dvFamily.Visible = true;

                btnSaveEducation.Visible = false;
                btnSaveFamily.Visible = true;

                ScriptManager.RegisterStartupScript(this, this.GetType(), "EditFamily", "openBackgroundModal();", true);
            }
        }

        protected void lnkAddFamily_Click(object sender, EventArgs e)
        {
            dvEducation.Visible = false;
            dvFamily.Visible = true;

            btnSaveEducation.Visible = false;
            btnSaveFamily.Visible = true;

            hdFamilyID.Value = "0";
            ClearFamilyForm();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "InsertFamily", "openBackgroundModal();", true);
        }

        private void ClearFamilyForm()
        {
            txtNameSurnanme.Text = "";
            ddlRelation.SelectedValue = "";
            txtOccupation.Text = "";
            txtLocation.Text = "";
        }

        protected void btnSaveFamily_Click(object sender, EventArgs e)
        {
            APP_FAMILY l;

            if (hdFamilyID.Value != "0")
            {
                l = FamilyDataSource.Where(o => o.GridIndex == Convert.ToInt16(hdFamilyID.Value)).FirstOrDefault();
            }
            else
            {
                l = new APP_FAMILY();
            }

            l.PERSONAL_ID = Convert.ToInt32(DSPersonal.ID);
            l.NAME = txtNameSurnanme.Text;
            l.OCCUPATION = txtOccupation.Text;
            l.LOCATION = txtLocation.Text;
            l.RELATION = ddlRelation.SelectedValue;
            l.ORD = 0;

            if (hdFamilyID.Value != "0")
            {
                l.act = ActionEnum.Edit;
            }
            else
            {
                l.act = ActionEnum.Add;
                FamilyDataSource.Add(l);

                FamilyDataSource = FamilyDataSource.Where(o => o.act != ActionEnum.Dummy).ToList();
            }

            BindTab2Family();

            hidFamily.Value = "1";
        }
        /* Stop Family Background */

        /* Start Education Background Code */
        protected void LoadEducationInfo()
        {
            if (DSPersonal.APP_EDUCATION.Count == 0)
            {
                APP_EDUCATION l = new APP_EDUCATION
                {
                    act = ActionEnum.Dummy,
                    DEGREE = "Bachelor's Degree",
                    INSTITUTE_NAME = "** Example University",
                    FROM_YEAR = "2002",
                    TO_YEAR = "2005",
                    GPA = "3.85",
                    MAJOR = "Business Administrator"
                };

                EducationDataSource.Add(l);
                hidEducation.Value = "";
            }
            else
            {
                hidEducation.Value = "1";
                EducationDataSource = DSPersonal.APP_EDUCATION.ToList();
            }

            BindTab2Education();
        }

        private void BindTab2Education()
        {
            RunEducationRowIndex(EducationDataSource);
            gvEducation.DataSource = EducationDataSource.Where(o => o.act != ActionEnum.Delete).ToList();
            gvEducation.DataBind();

            if (EducationDataSource.Where(o => o.act != ActionEnum.Delete && o.act != ActionEnum.Dummy).ToList().Count > 0)
                hidEducation.Value = "1";
            else
                hidEducation.Value = "";
        }

        protected void gvEducation_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "EditEducation")
            {
                hdEducationID.Value = e.CommandArgument.ToString();
                EditEducation(Convert.ToInt16(e.CommandArgument));
            }
            else //Delete Education
            {
                DeleteEducation(Convert.ToInt16(e.CommandArgument));

                List<APP_EDUCATION> lst = EducationDataSource.Where(o => o.act != ActionEnum.Delete).ToList();
                if (lst.Count == 0)
                    hidEducation.Value = "";
                else
                    hidEducation.Value = "1";
            }
        }

        private void DeleteEducation(int id)
        {
            APP_EDUCATION l = EducationDataSource.Where(o => o.GridIndex == id).FirstOrDefault();
            if (l != null)
            {
                l.act = ActionEnum.Delete;
                BindTab2Education();
            }
        }

        private void EditEducation(int id)
        {
            APP_EDUCATION l = EducationDataSource.Where(o => o.GridIndex == id).FirstOrDefault();
            if (l != null)
            {
                l.act = ActionEnum.Edit;
                txtNameOfInstitute.Text = l.INSTITUTE_NAME;
                ddlLevel.SelectedValue = l.DEGREE;
                txtFrom_Year.Text = l.FROM_YEAR;
                txtTo_Year.Text = l.TO_YEAR;
                txtGPA.Text = l.GPA;
                txtMajor.Text = l.MAJOR;

                dvEducation.Visible = true;
                dvFamily.Visible = false;

                btnSaveEducation.Visible = true;
                btnSaveFamily.Visible = false;

                ScriptManager.RegisterStartupScript(this, this.GetType(), "EditEducation", "openBackgroundModal();", true);
            }
        }

        protected void lnkAddEducation_Click(object sender, EventArgs e)
        {
            dvEducation.Visible = true;
            dvFamily.Visible = false;

            btnSaveEducation.Visible = true;
            btnSaveFamily.Visible = false;

            hdEducationID.Value = "0";
            ClearEducationForm();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "InsertEducation", "openBackgroundModal();", true);
        }

        private void ClearEducationForm()
        {
            txtNameOfInstitute.Text = "";
            ddlLevel.SelectedValue = "";
            txtFrom_Year.Text = "";
            txtTo_Year.Text = "";
            txtGPA.Text = "";
            txtMajor.Text = "";
        }

        protected void btnSaveEducation_Click(object sender, EventArgs e)
        {
            APP_EDUCATION l;

            if (hdEducationID.Value != "0")
            {
                l = EducationDataSource.Where(o => o.GridIndex == Convert.ToInt16(hdEducationID.Value)).FirstOrDefault();
            }
            else
            {
                l = new APP_EDUCATION();
            }

            l.PERSONAL_ID = Convert.ToInt32(DSPersonal.ID);
            l.DEGREE = ddlLevel.SelectedValue;
            l.INSTITUTE_NAME = txtNameOfInstitute.Text;
            l.FROM_YEAR = txtFrom_Year.Text;
            l.TO_YEAR = txtTo_Year.Text;
            l.GPA = txtGPA.Text;
            l.MAJOR = txtMajor.Text;

            if (hdEducationID.Value != "0")
            {
                l.act = ActionEnum.Edit;
            }
            else
            {
                l.act = ActionEnum.Add;
                EducationDataSource.Add(l);

                EducationDataSource = EducationDataSource.Where(o => o.act != ActionEnum.Dummy).ToList();
            }

            BindTab2Education();

            hidEducation.Value = "1";
        }
        /* Stop Education Background */

        protected void chkIsStudying_CheckedChanged(object sender, EventArgs e)
        {
            if (chkIsStudying.Checked == true)
                dvStudying.Visible = true;
            else
                dvStudying.Visible = false;
        }

        private void SaveFamilyAndEducation()
        {
            var cmdFamily = new MaintainFamilyCommand(FamilyDataSource.Where(o => o.act != ActionEnum.NoChange).ToList());
            cmdFamily.Execute();
            var cmdEducation = new MaintainEducationCommand(EducationDataSource.Where(o => o.act != ActionEnum.NoChange).ToList());
            cmdEducation.Execute();

            var P = DSPersonal;

            if (chkIsStudying.Checked == true)
            {
                P.IS_STUDYING = "Y";
            }
            else
            {
                P.IS_STUDYING = "N";
            }

            P.STUDYING_INSTITUTE = txtAtInstitute.Text;
            P.STUDYING_MAJOR = txtMajor2.Text;
            P.STUDYING_CLASS = txtClassScheduleDate.Text;
            P.STUDYING_FINISHON = txtFinishOn.Text;

            if(P.TX_STATUS == "1")
                P.TX_STATUS = "2";

            var cmdPersonal = new MaintainPersonalInfo(P);
            cmdPersonal.Execute();

            RefreshAllDataSource();
            RunFamilyRowIndex(FamilyDataSource);
            RunEducationRowIndex(EducationDataSource);
            BindTab2Family();
            BindTab2Education();
        }

        protected void btnTab2SaveDraft_Click(object sender, EventArgs e)
        {
            SaveFamilyAndEducation();
        }

        protected void btnTab2Next_Click(object sender, EventArgs e)
        {
            if (hidFamily.Value != "" && hidEducation.Value != "")
            {
                SaveFamilyAndEducation();
                TabActive++;
            }
        }

        #endregion

        #region Tab3

        public List<APP_EMPLOYER> EmployerDataSource
        {
            get
            {
                if (ViewState["EmployerList"] == null)
                {
                    ViewState["EmployerList"] = DSPersonal.APP_EMPLOYER.ToList();
                }

                return (List<APP_EMPLOYER>)ViewState["EmployerList"];
            }
            set
            {
                ViewState["EmployerList"] = value;
            }
        }

        private void RunEmployerRowIndex(List<APP_EMPLOYER> list)
        {
            int i = 0, j;

            foreach (APP_EMPLOYER emp in list)
            {
                if (emp.act != ActionEnum.Delete)
                {
                    emp.GridIndex = ++i;
                    j = 0;

                    foreach (APP_PROJECT proj in emp.APP_PROJECT)
                    {
                        if (proj.act != ActionEnum.Delete)
                        {
                            proj.GridIndex = ++j;
                            proj.CustomGridIndex = String.Format("{0}|{1}", i, j);
                        }
                    }
                }
            }
        }

        protected void LoadEmployer()
        {
            if (DSPersonal.APP_EMPLOYER.Count == 0)
            {
                APP_EMPLOYER e = new APP_EMPLOYER
                {
                    NAME = "ABC Company [Example]"
                    ,
                    ADDRESS = "Bangkok Thailand."
                    ,
                    BUS_TYPE = "IT"
                    ,
                    LAST_POSITION = "Developer"
                    ,
                    SUPERVISOR_NAME = "Mr. Doo"
                    ,
                    LEAV_REASON = "The reason"
                    ,
                    TOT_YEAR = "1"
                    ,
                    TOT_MTH = "3"
                    ,
                    SINCE = "Jan 2014"
                    ,
                    UNTIL = "Mar 2015"
                    ,
                    SRT_SALARY = 100
                    ,
                    LATEST_SALARY = 200
                    ,
                    BENEFITS = ""
                    ,
                    act = ActionEnum.Dummy
                };

                EmployerDataSource.Add(e);
                hidEmployment.Value = "";
            }
            else
                hidEmployment.Value = "1";

            BindTab3();
        }

        private void BindTab3()
        {
            RunEmployerRowIndex(EmployerDataSource);
            rptEmployer.DataSource = EmployerDataSource.Where(o => o.act != ActionEnum.Delete).ToList();
            rptEmployer.DataBind();
        }

        protected void rptEmployer_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
            {
                Repeater rptProj = (Repeater)e.Item.FindControl("rptProject");
                APP_EMPLOYER row = (APP_EMPLOYER)e.Item.DataItem;
                rptProj.DataSource = row.APP_PROJECT;
                rptProj.DataBind();
            }
        }

        protected void rptEmployer_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "AddProject")
            {
                AddProject(e.CommandArgument);
            }
            else if (e.CommandName == "EditEmp")
            {
                EditEmployer(Convert.ToInt16(e.CommandArgument));
            }
            else //DeleteEmp
            {
                DeleteEmployer(Convert.ToInt16(e.CommandArgument));

                List<APP_EMPLOYER> lst = EmployerDataSource.Where(o => o.act != ActionEnum.Delete).ToList();
                if (lst.Count == 0)
                    hidEmployment.Value = "";
                else
                    hidEmployment.Value = "1";
            }
        }

        protected void rptProject_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if(e.Item.ItemType == ListItemType.Footer)
            {
                if (((Repeater)sender).Items.Count == 0)
                {
                    Panel p = (Panel)e.Item.FindControl("pnlEmptyData");
                    p.Visible = true;
                }
            }
        }

        protected void rptProject_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "EditProject")
            {
                EditProject(e.CommandArgument.ToString());
            }
            else //DeleteProject
            {
                DeleteProject(e.CommandArgument.ToString());
            }
        }

        private void DeleteEmployer(int GridId)
        {
            APP_EMPLOYER e = EmployerDataSource.Where(o => o.GridIndex == GridId).FirstOrDefault();
            if (e != null)
            {
                e.act = ActionEnum.Delete;
                e.GridIndex = 0;
                BindTab3();
            }
        }

        private void EditEmployer(int GridId)
        {
            APP_EMPLOYER e = EmployerDataSource.Where(o => o.GridIndex == GridId).FirstOrDefault();
            if (e != null)
            {
                hdfEmployerId.Value = e.GridIndex.ToString();
                FillEmployerForm(e);
                ScriptManager.RegisterStartupScript(this, this.GetType(), "PopEmpEdit", "openEmployerModal();", true);
            }
        }

        private void DeleteProject(string GridIds)
        {
            string[] ids = GridIds.Split('|');
            int eid = Convert.ToInt16(ids[0]);
            int pid = Convert.ToInt16(ids[1]);

            APP_EMPLOYER e = EmployerDataSource.Where(o => o.GridIndex == eid).FirstOrDefault();
            if (e != null)
            {
                e.act = ActionEnum.Edit; //Fource edit if child is change

                APP_PROJECT p = e.APP_PROJECT.Where(o => o.GridIndex == pid).FirstOrDefault();
                p.act = ActionEnum.Delete;
            }

            BindTab3();
        }

        private void EditProject(string GridIds)
        {
            string[] ids = GridIds.Split('|');
            int eid = Convert.ToInt16(ids[0]);
            int pid = Convert.ToInt16(ids[1]);

            APP_EMPLOYER e = EmployerDataSource.Where(o => o.GridIndex == eid).FirstOrDefault();
            if (e != null)
            {
                e.act = ActionEnum.Edit; //Fource edit if child is change

                APP_PROJECT p = e.APP_PROJECT.Where(o => o.GridIndex == pid).FirstOrDefault();
                FillProjectForm(p);

                hdfEmployerId.Value = eid.ToString();
                hdfProjectId.Value = pid.ToString();
                ScriptManager.RegisterStartupScript(this, this.GetType(), "PopProjEdit", "openProjectModal();", true);
            }
        }

        protected void AddProject(object employerId)
        {
            APP_EMPLOYER e = EmployerDataSource.Where(o => o.GridIndex == Convert.ToInt16(employerId)).FirstOrDefault();
            if (e != null)
                e.act = ActionEnum.Edit;

            hdfEmployerId.Value = employerId.ToString();
            hdfProjectId.Value = "0";
            ClearProjectForm();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "PopProjEdit", "openProjectModal();", true);
        }

        protected void lnkAddEmployer_Click(object sender, EventArgs e)
        {
            hdfEmployerId.Value = "0";  //Case New Employer
            ClearEmployerForm();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "PopEmpEdit", "openEmployerModal();", true);
        }

        protected void FillEmployerForm(APP_EMPLOYER e)
        {
            txtEmployerName.Text = e.NAME;
            txtAddress.Text = e.ADDRESS;
            txtBusType.Text = e.BUS_TYPE;
            txtLastPos.Text = e.LAST_POSITION;
            txtSupName.Text = e.SUPERVISOR_NAME;
            txtLeaveReason.Text = e.LEAV_REASON;
            txtMonth.Text = e.TOT_MTH;
            txtYear.Text = e.TOT_YEAR;
            txtSince.Text = e.SINCE;
            txtUntil.Text = e.UNTIL;
            txtLatest.Text = UIHelper.DisplayNullableDecimal(e.LATEST_SALARY);
            txtStart.Text = UIHelper.DisplayNullableDecimal(e.SRT_SALARY);
            txtBenefith.Text = e.BENEFITS;
        }

        protected void FillProjectForm(APP_PROJECT p)
        {
            txtProjName.Text = p.PROJ_NAME;
            txtClientName.Text = p.CLIENT_NAME;
            txtPeriodFrom.Text = p.PERIOD_FROM;
            txtPeriodTo.Text = p.PERIOD_TO;
            txtRole.Text = p.ROLE;
            txtNumTeam.Text = p.TEAM;
            txtProjDesc.Text = p.PROJ_DESC;
            txtLanguage.Text = p.LANG;
            txtFramework.Text = p.FRAMEWORK;
            txtDB.Text = p.DB;
            txtOS.Text = p.OS;
            txtTools.Text = p.TOOLS;
        }

        protected void ClearEmployerForm()
        {
            txtEmployerName.Text = "";
            txtAddress.Text = "";
            txtBusType.Text = "";
            txtLastPos.Text = "";
            txtSupName.Text = "";
            txtLeaveReason.Text = "";
            txtMonth.Text = "";
            txtYear.Text = "";
            txtSince.Text = "";
            txtUntil.Text = "";
            txtLatest.Text = "";
            txtStart.Text = "";
            txtBenefith.Text = "";
        }

        protected void ClearProjectForm()
        {
            txtProjName.Text = "";
            txtClientName.Text = "";
            txtPeriodFrom.Text = "";
            txtPeriodTo.Text = "";
            txtRole.Text = "";
            txtNumTeam.Text = "";
            txtProjDesc.Text = "";
            txtLanguage.Text = "";
            txtFramework.Text = "";
            txtDB.Text = "";
            txtOS.Text = "";
            txtTools.Text = "";
        }

        protected void btnSaveEmployer_Click(object sender, EventArgs e)
        {
            APP_EMPLOYER emp;

            if (hdfEmployerId.Value != "0")
            {
                emp = EmployerDataSource.Where(o => o.GridIndex == Convert.ToInt32(hdfEmployerId.Value)).FirstOrDefault();
            }
            else
            {
                emp = new APP_EMPLOYER();
            }

            emp.PERSONAL_ID = DSPersonal.ID;
            emp.NAME = txtEmployerName.Text;
            emp.ADDRESS = txtAddress.Text;
            emp.BUS_TYPE = txtBusType.Text;
            emp.LAST_POSITION = txtLastPos.Text;
            emp.SUPERVISOR_NAME = txtSupName.Text;
            emp.LEAV_REASON = txtLeaveReason.Text;
            emp.TOT_MTH = txtMonth.Text;
            emp.TOT_YEAR = txtYear.Text;
            emp.SINCE = txtSince.Text;
            emp.UNTIL = txtUntil.Text;
            emp.LATEST_SALARY = UIHelper.GetNullableDecimalFromString(txtLatest.Text);
            emp.SRT_SALARY = UIHelper.GetNullableDecimalFromString(txtStart.Text);
            emp.BENEFITS = txtBenefith.Text;

            if (hdfEmployerId.Value != "0")
                emp.act = ActionEnum.Edit;
            else
            {
                emp.act = ActionEnum.Add;
                EmployerDataSource.Add(emp);
            }

            EmployerDataSource = EmployerDataSource.Where(o => o.act != ActionEnum.Dummy).ToList();

            BindTab3();

            hidEmployment.Value = "1";
        }

        protected void btnSaveProject_Click(object sender, EventArgs e)
        {
            APP_EMPLOYER emp = EmployerDataSource.Where(o => o.GridIndex == Convert.ToInt32(hdfEmployerId.Value)).FirstOrDefault();
            APP_PROJECT proj;

            if (hdfProjectId.Value != "0")
            {
                proj = emp.APP_PROJECT.Where(b => b.GridIndex == Convert.ToInt16(hdfProjectId.Value)).FirstOrDefault();
            }
            else
            {
                proj = new APP_PROJECT();
            }

            proj.EID = emp.ID;
            proj.PROJ_NAME = txtProjName.Text;
            proj.CLIENT_NAME = txtClientName.Text;
            proj.PERIOD_FROM = txtPeriodFrom.Text;
            proj.PERIOD_TO = txtPeriodTo.Text;
            proj.ROLE = txtRole.Text;
            proj.TEAM = txtNumTeam.Text;
            proj.PROJ_DESC = txtProjDesc.Text;
            proj.LANG = txtLanguage.Text;
            proj.FRAMEWORK = txtFramework.Text;
            proj.DB = txtDB.Text;
            proj.OS = txtOS.Text;
            proj.TOOLS = txtTools.Text;

            if (hdfProjectId.Value != "0")
                proj.act = ActionEnum.Edit;
            else
            {
                proj.act = ActionEnum.Add;
                emp.APP_PROJECT.Add(proj);
            }

            BindTab3();
        }

        protected void btnSaveDraftExp_Click(object sender, EventArgs e)
        {
            SaveEmployment();
        }

        protected void SaveEmployment()
        {
            MaintainEmployerCommand cmd = new MaintainEmployerCommand(EmployerDataSource.Where(o => o.act != ActionEnum.NoChange && o.act != ActionEnum.Dummy).ToList());
            cmd.Execute();

            var P = DSPersonal;
            if (P.TX_STATUS == "2")
            {
                P.TX_STATUS = "3";

                var cmdPersonal = new MaintainPersonalInfo(P);
                cmdPersonal.Execute();
            }

            RefreshAllDataSource();

            RunEmployerRowIndex(EmployerDataSource);
            BindTab3();
        }

        protected void btnNextExp_Click(object sender, EventArgs e)
        {
            SaveEmployment();
            if (hidEmployment.Value != "")
            {
                TabActive++;
            }
        }

        #endregion

        #region Tab4

        public List<APP_LANGUAGE> LanguageDataSource
        {
            get
            {
                if (ViewState["LanguageDataSource"] == null)
                    ViewState["LanguageDataSource"] = DSPersonal.APP_LANGUAGE.ToList();

                return (List<APP_LANGUAGE>)ViewState["LanguageDataSource"];
            }
            set
            {
                ViewState["LanguageDataSource"] = value;
            }
        }

        public string SkillProg
        {
            set
            {
                if (DSPersonal.PRG_LANG_SKILL != "[]" && DSPersonal.PRG_LANG_SKILL != "" && DSPersonal.PRG_LANG_SKILL != null)
                {
                    tagsProgramming.Value = value;
                    chkProg.Checked = true;
                }
                else
                    chkProg.Checked = false;
            }

            get
            {
                return tagsProgramming.Value;
            }
        }

        public string SkillReport
        {
            set
            {
                if (DSPersonal.REPORT_SKILL != "[]" && DSPersonal.REPORT_SKILL != "" && DSPersonal.REPORT_SKILL != null)
                {
                    tagsReport.Value = value;
                    chkReport.Checked = true;
                }
                else
                    chkReport.Checked = false;
            }

            get
            {
                return tagsReport.Value;
            }
        }

        public string SkillDB
        {
            set
            {
                if (DSPersonal.DB_SKILL != "[]" && DSPersonal.DB_SKILL != "" && DSPersonal.DB_SKILL != null)
                {
                    tagsDB.Value = value;
                    chkDatabase.Checked = true;
                }
                else
                    chkDatabase.Checked = false;
            }

            get
            {
                return tagsDB.Value;
            }
        }

        public string SkillFramework
        {
            set
            {
                if (DSPersonal.FRAMEWORK_SKILL != "[]" && DSPersonal.FRAMEWORK_SKILL != "" && DSPersonal.FRAMEWORK_SKILL != null)
                {
                    tagsFramework.Value = value;
                    chkFramework.Checked = true;
                }
                else
                    chkFramework.Checked = false;
            }

            get
            {
                return tagsFramework.Value;
            }
        }

        public string SkillTool
        {
            set
            {
                if (DSPersonal.TOOLS_SKILL != "[]" && DSPersonal.TOOLS_SKILL != "" && DSPersonal.TOOLS_SKILL != null)
                {
                    tagsTool.Value = value;
                    chkDevTools.Checked = true;
                }
                else
                    chkDevTools.Checked = false;
            }

            get
            {
                return tagsTool.Value;
            }
        }

        public string SkillSoftTest
        {
            set
            {
                if (DSPersonal.TESTING_SKILL != "[]" && DSPersonal.TESTING_SKILL != "" && DSPersonal.TESTING_SKILL != null)
                {
                    tagsSofttest.Value = value;
                    chkSoftTest.Checked = true;
                }
                else
                    chkSoftTest.Checked = false;
            }

            get
            {
                return tagsSofttest.Value;
            }
        }

        public string SkillOS
        {
            set
            {
                if (DSPersonal.OS_SKILL != "[]" && DSPersonal.OS_SKILL != "" && DSPersonal.OS_SKILL != null)
                {
                    tagsOS.Value = value;
                    chkOS.Checked = true;
                }
                else
                    chkOS.Checked = false;
            }

            get
            {
                return tagsOS.Value;
            }
        }
       
        public string SkillOther
        {
            set
            {
                if (DSPersonal.OTHER_SKILL != "[]" && DSPersonal.OTHER_SKILL != "" && DSPersonal.OTHER_SKILL != null)
                {
                    tagsOther.Value = value;
                    chkOther.Checked = true;
                }
                else
                    chkOther.Checked = false;
            }

            get
            {
                return tagsOther.Value;
            }
        }

        private void RunLanguageRowIndex(List<APP_LANGUAGE> list)
        {
            int i = 0;

            foreach (APP_LANGUAGE l in list)
            {
                if (l.act != ActionEnum.Delete)
                    l.GridIndex = ++i;
            }
        }

        private void LoadSkillAndLang()
        {

            if (DSPersonal.APP_LANGUAGE.Count == 0)
            {
                APP_LANGUAGE l = new APP_LANGUAGE
                {
                    act = ActionEnum.Dummy,
                    LANG_NAME = "ไทย [Example]",
                    READING = "Good",
                    WRITING = "Good",
                    UNDERSTAND = "Good",
                    SPEAKING = "Good"
                };

                LanguageDataSource.Add(l);
            }

            BindTab4();

        }

        private void BindTab4()
        {
            SkillProg = DSPersonal.PRG_LANG_SKILL;
            SkillReport = DSPersonal.REPORT_SKILL;
            SkillDB = DSPersonal.DB_SKILL;
            SkillTool = DSPersonal.TOOLS_SKILL;
            SkillFramework = DSPersonal.FRAMEWORK_SKILL;
            SkillSoftTest = DSPersonal.TESTING_SKILL;
            SkillOS = DSPersonal.OS_SKILL;
            SkillOther = DSPersonal.OTHER_SKILL;            

            RunLanguageRowIndex(LanguageDataSource);
            grdLanguage.DataSource = LanguageDataSource.Where(o => o.act != ActionEnum.Delete).ToList();
            grdLanguage.DataBind();
        }

        protected void grdLanguage_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "EditLanguage")
            {
                hdfLangID.Value = e.CommandArgument.ToString();
                EditLanguage(Convert.ToInt16(e.CommandArgument));
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop2", "openLangModal();", true);
            }
            else //DeleteLAnguage
            {
                DeleteLanguage(Convert.ToInt16(e.CommandArgument));
            }
        }

        private void DeleteLanguage(int id)
        {
            APP_LANGUAGE l = LanguageDataSource.Where(o => o.GridIndex == id).FirstOrDefault();
            if (l != null)
            {
                l.act = ActionEnum.Delete;
                l.GridIndex = 0;
                BindTab4();
            }
        }

        private void EditLanguage(int id)
        {
            APP_LANGUAGE l = LanguageDataSource.Where(o => o.GridIndex == id).FirstOrDefault();
            if (l != null)
            {
                l.act = ActionEnum.Edit;
                txtSKillLanguage.Text = l.LANG_NAME;
                rbReading.SelectedValue = l.READING;
                rbSpeaking.SelectedValue = l.SPEAKING;
                rbUnderstand.SelectedValue = l.UNDERSTAND;
                rbWriting.SelectedValue = l.UNDERSTAND;

                BindTab4();
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop2", "openLangModal();", true);
            }
        }

        protected void lnkAddLanguage_Click(object sender, EventArgs e)
        {
            hdfLangID.Value = "0";
            ClearLangForm();
            BindTab4();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop2", "openLangModal();", true);
        }

        private void ClearLangForm()
        {
            txtSKillLanguage.Text = "";
            rbReading.SelectedIndex = -1;
            rbSpeaking.SelectedIndex = -1;
            rbUnderstand.SelectedIndex = -1;
            rbWriting.SelectedIndex = -1;
        }

        protected void btnSaveLanguage_Click(object sender, EventArgs e)
        {
            APP_LANGUAGE l;

            if (hdfLangID.Value != "0")
            {
                l = LanguageDataSource.Where(o => o.GridIndex == Convert.ToInt16(hdfLangID.Value)).FirstOrDefault();
            }
            else
            {
                l = new APP_LANGUAGE();
            }

            l.PERSONAL_ID = DSPersonal.ID;
            l.LANG_NAME = txtSKillLanguage.Text;
            l.READING = rbReading.SelectedValue;
            l.SPEAKING = rbSpeaking.SelectedValue;
            l.UNDERSTAND = rbUnderstand.SelectedValue;
            l.WRITING = rbWriting.SelectedValue;

            if (hdfLangID.Value != "0")
            {
                l.act = ActionEnum.Edit;
            }
            else
            {
                l.act = ActionEnum.Add;
                LanguageDataSource.Add(l);
            }

            LanguageDataSource = LanguageDataSource.Where(o => o.act != ActionEnum.Dummy).ToList();

            BindTab4();
        }

        protected void btnSaveDraftLang_Click(object sender, EventArgs e)
        {
            SaveSkillAndLang();
        }

        protected void btnNextLang_Click(object sender, EventArgs e)
        {
            SaveSkillAndLang();
            TabActive++;
        }

        protected void SaveSkillAndLang()
        {
            //Save lang list
            MaintainLanguageCommand cmd = new MaintainLanguageCommand(LanguageDataSource.Where(o => o.act != ActionEnum.NoChange).ToList());
            cmd.Execute();

            //Save skill
            DSPersonal.PRG_LANG_SKILL = SkillProg;
            DSPersonal.REPORT_SKILL = SkillReport;
            DSPersonal.DB_SKILL = SkillDB;
            DSPersonal.TOOLS_SKILL = SkillTool;
            DSPersonal.FRAMEWORK_SKILL = SkillFramework;
            DSPersonal.OS_SKILL = SkillOS;
            DSPersonal.TESTING_SKILL = SkillSoftTest;
            DSPersonal.OTHER_SKILL = SkillOther;

            if (DSPersonal.TX_STATUS == "3")
            {
                DSPersonal.TX_STATUS = "4";
                MaintainPersonalInfo pcmd = new MaintainPersonalInfo(DSPersonal);
                pcmd.Execute();
            }

            RefreshAllDataSource();
            RunLanguageRowIndex(LanguageDataSource);
            BindTab4();
        }

        #endregion

        #region Tab5

        private void LoadSalary()
        {
            txtExpSalary.Text = DSPersonal.EXPECT_SALARY.ToString();
        }

        protected void btnSubmitSalary_Click(object sender, EventArgs e)
        {
            DSPersonal.EXPECT_SALARY = Convert.ToDecimal(txtExpSalary.Text);
            MaintainPersonalInfo cmd = new MaintainPersonalInfo(DSPersonal);
            cmd.Execute();

            TabActive++;
        }

        #endregion
        
    }
}